package cash_access;

import java.io.IOException;

import mware_lib.communication.ObjectStream;
import mware_lib.messages.ReqAccMsg;
import mware_lib.messages.RetAccMsg;

public class AccountWorker implements Runnable{
	private volatile boolean running;
    private Thread thread;
    
    private Account account;
    private ReqAccMsg reqMsg;
    private ObjectStream os;
    
    public AccountWorker(Account account, ReqAccMsg invokeMsg, ObjectStream os){
        this.running = true;
        this.thread = new Thread(this);
        this.account = account;
        this.reqMsg = invokeMsg;
        this.os = os;
    }
    
   
    @Override
    public void run() {
        while(this.running){
            RetAccMsg result = null;
            try {
                if (this.reqMsg.getMethod().equals("deposit")){
                    if(this.reqMsg.getMethod()== null || this.reqMsg.getKtoID() == null){
                        result = new RetAccMsg("IllegalParameterException");
                    } else {
                        Double amount = (Double)this.reqMsg.getAmount();
                        this.account.deposit(amount);
                        result = new RetAccMsg(null);
                    }
                } else if (this.reqMsg.getMethod().equals("withdraw")){
                    if(this.reqMsg.getMethod()== null || this.reqMsg.getKtoID() == null ){
                        result = new RetAccMsg("IllegalParameterException");
                    } else {
                        Double amount = (Double)this.reqMsg.getAmount();
                        try {
                            this.account.withdraw(amount);
                            result = new RetAccMsg(null);
                        } catch (NumberFormatException e) {
                            result = new RetAccMsg("IllegalParameterException : "+amount.toString());
                        }
                    }
                } else if (this.reqMsg.getMethod().equals("getBalance")){
                    Double balance = new Double(this.account.getBalance());
                    result = new RetAccMsg(balance);
                } else {
                    result = new RetAccMsg( "UnknownMethodException: "+ (this.reqMsg.getMethod()) );
                }
            } catch (Exception e) {
                result = new RetAccMsg(e);
            }
            try {
                this.os.send(result);
            } catch (IOException e1) { e1.printStackTrace();
            } finally {
                this.stop();
                try {
                    this.os.closeSocket();
                } catch (IOException e) { }
            }
        }
    }
    
    
    public void stop(){
        this.running = false;
    }
    
    public void start(){
        this.thread.start();
    }

}
